define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'user/user/index',
                    add_url: 'user/user/add',
                    edit_url: 'user/user/edit',
                    del_url: 'user/user/del',
                    import_url: 'user/user/import',
                    multi_url: 'user/user/multi',
                    table: 'user',
                }
            });

            var table = $("#table");

            $(".btn-add").data("area", ["100%", "100%"]);

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'user.id',
                Search:true,
                commonSearch:true,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true,operate: false,visible:false},
                        // {field: 'code', title: __('用户编号'), operate: false},
                        {field: 'nickname', title: __('Nickname'), operate: 'LIKE'},
                        {field: 'avatar', title: __('Avatar'), events: Table.api.events.image, formatter: Table.api.formatter.image, operate: false},
                        // {field: 'juser.nickname', title: __('推荐人'), operate: false},
                        {field: 'username', title: __('Username'), operate: 'LIKE'},
                        {field: 'tag_id', searchList: $.getJSON('ajax/gettaglist'),title: __('标签'),visible:false},
                        {field: 'tagsname', title: '标签', operate: false},
                        {field: 'mobile', title: __('Mobile'), operate: 'LIKE'},
                        {field: 'group.id', searchList: $.getJSON('ajax/getgrouplist'),title: __('Group'),visible:false},
                        {field: 'group.name', searchList: $.getJSON('ajax/getgrouplist'),title: __('Group'),operate:false},
                        {field: 'ordercount', title: __('消费次数'), operate: false},
                        {field: 'orderfee', title: __('消费金额'), operate: false},
                        {field: 'orderdate', title: __('上次消费时间'), operate: false},
                        {field: 'cardnumber', title: __('持卡'), operate: false},
                        {field: 'money', title: __('money'), operate: 'BETWEEN', sortable: true},
                        {field: 'shop.shopname', title: __('归属门店'), operate:false},
                        {field: 'status', title: __('Status'), formatter: Table.api.formatter.status, searchList: {normal: __('Normal'), hidden: __('拉黑')},operate:false},
                        {field: 'createtime', title: __('注册时间'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'jointime', title: __('加入时间'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        //{field: 'email', title: __('Email'), operate: 'LIKE'},
                        
                      
                        //{field: 'level', title: __('Level'), operate: 'BETWEEN', sortable: true},
                        // {field: 'gender', title: __('Gender'), visible: false, searchList: {1: __('Male'), 0: __('Female')}},
                         // {field: 'score', title: __('Score'), operate: false, sortable: true},
                         
                        // {field: 'successions', title: __('Successions'), visible: false, operate: 'BETWEEN', sortable: true},
                        // {field: 'maxsuccessions', title: __('Maxsuccessions'), visible: false, operate: 'BETWEEN', sortable: true},
                        // {field: 'logintime', title: __('Logintime'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                        // {field: 'loginip', title: __('Loginip'), formatter: Table.api.formatter.search},
                        
                        //{field: 'joinip', title: __('Joinip'), formatter: Table.api.formatter.search},
                        
                        // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons :[
                                {
                                    name: 'detail',
                                    text: '详情',
                                    title: '查看用户详情',
                                    icon: '',
                                    extend: 'data-area=\'["100%", "100%"]\'',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: 'user/user/detail'
                                },
                                {
                                    name: 'billing',
                                    text: '开单',
                                    title: '开单',
                                    icon: '',
                                    extend:' target="_blank"',
                                    classname: 'btn btn-xs btn-primary',
                                    url: function(row) {
                                        return '/cashdesk';
                                    }
                                }
                            ],
                            callback: function (data) {
                                table.bootstrapTable('refresh', {});
                                return false;
                            },
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        import: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
            Form.api.bindevent("form[role=form]", function(data, ret){
                parent.$(".btn-refresh").trigger("click");
                Fast.api.close();
                return false;
            });
        },
        detail: function () {
            var user_id = Config.user_id;
            $(document).on("click", ".items li", function () {
                var cur_index = $('.items li').index(this);
                $('.items .nav-pills-active').removeClass('nav-pills-active');
                $('.items li').eq(cur_index).addClass('nav-pills-active');
                $('.item-list').hide();
                $('.item-list').eq(cur_index).show();
            });
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/goodsorder/userOrder?user_id='+user_id,
                    table: 'wanlshop_order',
                }
            });

            var table = $("#order_table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                responseHandler: function(res) {
                    // 假设res包含total字段表示总记录数
                    var total = res.total;
                    $('.trade_number').text('交易记录（'+total+'）'); // 将总数显示在一个具有id="data-count"的元素中
                    return res; // 返回原始数据以便继续渲染表格
                },
                // Search:true,
                // commonSearch:true,
                // searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false},
                        {field: 'order_no', title: __('订单编号'), operate: 'LIKE'},
                        {field: 'goods_name', title: __('商品名称'), operate: false, table: table, class: 'autocontent',formatter: function(value) {
                                //const arr = value.split(',');
                                var html="";
                                //console.log(value);
                                // for (var i=0;i++;arr.length){
                                //     html +="<div>"+arr[i]+"</div>";
                                // }
                                $.each(value,function (index,val) {

                                    html +='<div style="text-align: left;">'+val.name + (val.is_gift==1 ? '<span style="color:#f75444">（赠）</span>':'') + '</div>';
                                });

                                return html;
                            }},
                        {field: 'price', title: __('总价'), operate: false},
                        {field: 'actual_price', title: __('实际支付'), operate: false},
                        {field: 'state', title: __('订单状态'), searchList: {"1":__('State 1'),"2":__('State 2'),"3":__('State 3'),"4":__('State 4'),"6":__('State 6'),"7":__('State 7')}, formatter: Table.api.formatter.normal},
                        {field: 'paymenttime', title: __('付款时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'shop.shopname', title: '下单门店', operate: 'LIKE'},
                         {field: 'operate', title: __('付款时间'), table: table, events: Table.api.events.operate,
                            
                            buttons: [{
                                name: "test",
                                text: "查看/编辑",//按钮名称
                                classname: 'btn btn-xs btn-success btn-magic ',
                                // classname: 'btn btn-xs btn-success btn-magic btn-dialog',
                                icon: 'fa fa-magic',
                                url:function(row){
                                    if(row.data_type=='goods'){
                                        return "/fQTrLEivaP.php/order/goodsorder/detail?ids="+row.id;//指向控制器对应方法
                                    }else {
                                        return "/fQTrLEivaP.php/order/itemorder/detail?ids="+row.id;//指向控制器对应方法
                                    }
                                },
                                confirm: '查看/编辑息',
                                visible: function (row) {
                                    //返回true时按钮显示,返回false隐藏
                                    return true;
                                }
                            }],
                            formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            Controller.api.bindevent();

            $(document).on("click", ".edit-user", function () {
                var data_url=$(this).data("url");
                var data_id =$(this).data("id");
                if(!data_url) return false;
                var edit_url = data_url+'/ids/'+data_id;
                Fast.api.open(edit_url,"编辑用户信息",{
                    area:['100%','100%'],
                    callback:function(value){
                        parent.$(".btn-refresh").trigger("click");
                        window.location.reload(true);
                        return false;
                        
                    }
                });
            });

            $(document).on("click", ".set-tags", function () {
                var data_url=$(this).data("url");
                var data_id =$(this).data("id");
                if(!data_url) return false;
                var edit_url = data_url+'/ids/'+data_id;
                Fast.api.open(edit_url,"设置标签",{
                    area:['100%','100%'],
                    callback:function(value){
                        parent.$(".btn-refresh").trigger("click");
                        window.location.reload(true);
                        return false;
                        
                    }
                });
            });

            $(document).on("click", ".delete-item", function () {
                var itemid = $(this).data('itemid');
                 Fast.api.ajax({
                    url: 'user/user/delitem',
                    data: {ids:itemid}
                }, function(data, ret) {
                    window.location.reload(true);
                    return false;
                });
            });

            $(document).on("click", ".delete-server", function () {
                var itemid = $(this).data('itemid');
                 Fast.api.ajax({
                    url: 'user/user/delserver',
                    data: {ids:itemid}
                }, function(data, ret) {
                    if (ret.code == 1) {
                        var obj = $('#service'+itemid);
                        obj.css('background','#edf2fa');
                        obj.find('.item-status').removeClass('delete-server');
                        obj.find('.status_text').text('已失效');
                    }
                });
            });

            //保存自定义标签信息
            $(document).on("click", ".save-tag-info", function () {
                var add_tag_url = $('.btn-tag-add').data('url');
                var user_id = $('.btn-tag-add').data('id');
                var tag_name = $('.tag-name').val();
                if (tag_name == '') {
                    alert('请填写标签名称');
                    return false;
                }

                Fast.api.ajax({
                    url: add_tag_url,
                    data: {
                        tag_name: tag_name,
                        user_id: user_id,
                    }
                }, function(data, ret) {
                    window.location.reload(true);
                    return false;
                });
            });

        },
        addusertag: function () {
            Controller.api.bindevent();
            $(document).on("click", ".tag-add", function () {
                $(this).removeClass('tag-add').addClass('label-item-selected');
                $tag_html = '<span class="label label-item" data-id="'+$(this).data('id')+'">'+$(this).text()+' <i class="fa fa-close tag-del"></i><input type="hidden" name="row[tag_id][]" value="'+$(this).data('id')+'"></span> ';
                $('.tag-selected-list>.p-2').append($tag_html);
                var tag_count = $('.tag-selected-list>.p-2>.label-item').length;
                $('.tag-count').html(tag_count);
            });

            $(document).on("click", ".tag-del", function () {
                var data_id = $(this).parent('span').data('id');
                $('span[data-id="'+data_id+'"]').removeClass('label-item-selected').addClass('tag-add');
                $(this).parent('span').remove();
                var tag_count = $('.tag-selected-list>.p-2>.label-item').length;
                $('.tag-count').html(tag_count);
            });
            
            //单项收起
            $(document).on("click", ".title-toggle-down", function () {
                var tag_item_list_html = $(this).html().replace("fa-chevron-down", "fa-chevron-up");
                $(this).removeClass('title-toggle-down').addClass('title-toggle-up').html(tag_item_list_html);
                $(this).next('.tag-item-list').show();
            });
            
            //单项展开
            $(document).on("click", ".title-toggle-up", function () {
                var tag_item_list_html = $(this).html().replace("fa-chevron-up", "fa-chevron-down");
                $(this).removeClass('title-toggle-up').addClass('title-toggle-down').html(tag_item_list_html);
                $(this).next('.tag-item-list').hide();
            });

            //全部收起
            $(document).on("click", ".toggle-up", function () {
                $(this).removeClass('toggle-up').addClass('toggle-down').html('<i class="fa fa-plus"> 全部展开</i>');
                $('.tag-div-title').each(function(){
                    var tag_item_list_html = $(this).html().replace("fa-chevron-up", "fa-chevron-down");
                    $(this).removeClass('title-toggle-up').addClass('title-toggle-down').html(tag_item_list_html);
                });
                $('.tag-item-list').hide();
            });

            //全部展开
            $(document).on("click", ".toggle-down", function () {
                $(this).removeClass('toggle-down').addClass('toggle-up').html('<i class="fa fa-minus"> 全部收起</i>');
                $('.tag-div-title').each(function(){
                    var tag_item_list_html = $(this).html().replace("fa-chevron-down", "fa-chevron-up");
                    $(this).removeClass('title-toggle-down').addClass('title-toggle-up').html(tag_item_list_html);
                });
                $('.tag-item-list').show();
            });

            //保存自定义标签信息
            $(document).on("click", ".save-tag-info", function () {
                var add_tag_url = $('.btn-tag-add').data('url');
                var tag_name = $('.tag-name').val();
                if (tag_name == '') {
                    alert('请填写标签名称');
                    return false;
                }

                Fast.api.ajax({
                    url: add_tag_url,
                    data: {
                        tag_name: tag_name
                    }
                }, function(data, ret) {
                    window.location.reload(true);
                    return false;
                });
            });

            Form.api.bindevent("form[role=form]", function(data, ret){
                parent.$(".btn-refresh").trigger("click");
                Fast.api.close();
                return false;
            });
        },
        addtag: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});